cmake_minimum_required(VERSION 3.24)
project(MarathonRewriteCore LANGUAGES C CXX OBJCXX)

# Headless Marathon simulation core, extracted from Aleph One 1.11.1 (ao/)
# plus our session, stubs and sim/ code. Every change is checked against the
# 101 AO test films (tools/run_core_film_tests.sh). See docs/extraction-map.md.

set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_EXTENSIONS ON)
set(CMAKE_C_STANDARD 11)
set(CMAKE_OBJCXX_STANDARD 17)
if(NOT CMAKE_BUILD_TYPE)
  set(CMAKE_BUILD_TYPE RelWithDebInfo)
endif()
# MR_DIST: a build to hand out. No paths from this machine end up in the
# binary (__FILE__ is made relative; the build-tree data fallbacks are left out).
option(MR_DIST "Build for distribution" OFF)
if(MR_DIST)
  get_filename_component(MR_ROOT "${CMAKE_CURRENT_SOURCE_DIR}/.." ABSOLUTE)
  add_compile_options("-ffile-prefix-map=${MR_ROOT}/=" "-ffile-prefix-map=${CMAKE_CURRENT_SOURCE_DIR}/=core/")
endif()

find_package(PkgConfig REQUIRED)
# Homebrew keeps openal-soft and libzzip out of the default pkg-config path.
execute_process(COMMAND brew --prefix OUTPUT_VARIABLE BREW OUTPUT_STRIP_TRAILING_WHITESPACE)
set(ENV{PKG_CONFIG_PATH} "${BREW}/opt/openal-soft/lib/pkgconfig:${BREW}/opt/libzzip/lib/pkgconfig:$ENV{PKG_CONFIG_PATH}")
# Linked: SDL2 (surfaces, file I/O), SDL2_ttf (font metrics: terminal paging
# depends on them), SDL2_image (terminal pictures), zziplib (zipped plugins).
pkg_check_modules(DEPS REQUIRED IMPORTED_TARGET sdl2 SDL2_ttf SDL2_image zlib zziplib)
# Headers only: AO's sound headers (included by game code) need OpenAL and
# libsndfile declarations; nothing from them is linked.
pkg_check_modules(SOUND_HEADERS REQUIRED openal sndfile)
# Network layer only: curl for AO's HTTP client (metaserver/updates).
pkg_check_modules(NETDEPS REQUIRED IMPORTED_TARGET libcurl)
cmake_policy(SET CMP0167 OLD)
find_package(Boost REQUIRED COMPONENTS filesystem)

# tools/try_remove.py points this at a trial copy of the list.
set(AO_SOURCES_FILE "${CMAKE_CURRENT_SOURCE_DIR}/ao_sources.cmake" CACHE FILEPATH "Source list")
include(${AO_SOURCES_FILE})

# Lua 5.x interpreter (AO's bundled copy), for map/solo/net/HUD/stats scripts.
add_library(lua_lib STATIC
  ao/Lua/lapi.c
  ao/Lua/lauxlib.c
  ao/Lua/lbaselib.c
  ao/Lua/lbitlib.c
  ao/Lua/lcode.c
  ao/Lua/lctype.c
  ao/Lua/ldblib.c
  ao/Lua/ldebug.c
  ao/Lua/ldo.c
  ao/Lua/ldump.c
  ao/Lua/lfunc.c
  ao/Lua/lgc.c
  ao/Lua/linit.c
  ao/Lua/liolib.c
  ao/Lua/llex.c
  ao/Lua/lmathlib.c
  ao/Lua/lmem.c
  ao/Lua/lobject.c
  ao/Lua/lopcodes.c
  ao/Lua/loslib.c
  ao/Lua/lparser.c
  ao/Lua/lstate.c
  ao/Lua/lstring.c
  ao/Lua/lstrlib.c
  ao/Lua/ltable.c
  ao/Lua/ltablib.c
  ao/Lua/ltm.c
  ao/Lua/lundump.c
  ao/Lua/lvm.c
  ao/Lua/lzio.c)
set_target_properties(lua_lib PROPERTIES LINKER_LANGUAGE C)
target_compile_options(lua_lib PRIVATE -w)
target_compile_definitions(lua_lib PRIVATE LUA_USE_MACOSX)
add_library(ao_all STATIC ${AO_SOURCES})
file(GLOB AO_DIRS LIST_DIRECTORIES true ${CMAKE_CURRENT_SOURCE_DIR}/ao/*)
list(FILTER AO_DIRS EXCLUDE REGEX "\\.[a-z]+$")
target_include_directories(ao_all PUBLIC
  ${CMAKE_CURRENT_SOURCE_DIR}            # config.h
  ${CMAKE_CURRENT_SOURCE_DIR}/ao
  ${CMAKE_CURRENT_SOURCE_DIR}/session
  ${CMAKE_CURRENT_SOURCE_DIR}/sim
  ${AO_DIRS}
  ${CMAKE_CURRENT_SOURCE_DIR}/ao/Network/Metaserver
  ${BREW}/include
  ${SOUND_HEADERS_INCLUDE_DIRS})
target_compile_definitions(ao_all PUBLIC HAVE_CONFIG_H __DARWIN__)
# AO's own warnings are off (not ours to fix yet). -DMR_WARN_NARROWING=ON
# shows only integers squeezed into smaller types (used to find 16-bit map
# indexes when widening them; see docs/map-limits.md).
option(MR_WARN_NARROWING "Warn about implicit integer narrowing in the AO core" OFF)
if(MR_WARN_NARROWING)
  target_compile_options(ao_all PRIVATE -Wno-everything -Wimplicit-int-conversion)
else()
  target_compile_options(ao_all PRIVATE -w)
endif()
target_link_libraries(ao_all PUBLIC lua_lib PkgConfig::DEPS Boost::filesystem
  "-framework Foundation" "-framework AppKit" "-framework Cocoa")

# Headless-ish film runner (still opens an SDL window in stage A).
# Must be an .app: AO's cspaths.mm reads the app name from the bundle.
# The runner links the viewer's HUD code too, so --mesh-every-tick also proves
# the HUD and the real motion sensor never change the game.
add_executable(film_runner MACOSX_BUNDLE runner/film_runner.cpp runner/world_trace.cpp runner/font_report.cpp renderer/world_mesh.cpp
  renderer/hud/hud.cpp
  renderer/hud/motion_sensor.cpp
  renderer/hud/overhead_map.cpp renderer/hud/OverheadMapRenderer.cpp renderer/hud/OverheadMap_SDL.cpp
  runner/InfoPlist.strings)
set_source_files_properties(runner/InfoPlist.strings PROPERTIES MACOSX_PACKAGE_LOCATION Resources/en.lproj)
set_target_properties(film_runner PROPERTIES
  MACOSX_BUNDLE_INFO_PLIST ${CMAKE_CURRENT_SOURCE_DIR}/runner/Info.plist.in
  OUTPUT_NAME film_runner)
target_include_directories(film_runner PRIVATE renderer renderer/hud)
target_link_libraries(film_runner PRIVATE ao_all)
# Linker map: which AO object files actually end up in the runner.
target_link_options(film_runner PRIVATE "-Wl,-map,${CMAKE_BINARY_DIR}/film_runner.map" "-Wl,-dead_strip_dylibs")

# Viewer audio: AO 1.11.1's own sound code (copied into renderer/audio/),
# replacing the core's silent stubs/sound_stub.cpp for the viewer only.
file(GLOB VIEWER_AUDIO_SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/renderer/audio/*.cpp)
pkg_check_modules(AUDIO REQUIRED IMPORTED_TARGET openal sndfile vorbis)

# Metal viewer (roadmap step 3). Same .app requirement as the film runner.
add_executable(viewer MACOSX_BUNDLE
  renderer/viewer_main.mm renderer/launcher.mm renderer/title_music.mm renderer/bindings.mm renderer/keychain.mm renderer/term_ui.mm renderer/waiting_room.mm renderer/lobby_window.mm renderer/messages.mm renderer/metal_renderer.mm renderer/crosshairs.cpp renderer/world_mesh.cpp
  renderer/hud/hud.cpp
  renderer/hud/motion_sensor.cpp
  renderer/hud/overhead_map.cpp renderer/hud/OverheadMapRenderer.cpp renderer/hud/OverheadMap_SDL.cpp
  ${VIEWER_AUDIO_SOURCES}
  runner/InfoPlist.strings)
set_source_files_properties(runner/InfoPlist.strings PROPERTIES MACOSX_PACKAGE_LOCATION Resources/en.lproj)
set_target_properties(viewer PROPERTIES
  MACOSX_BUNDLE_INFO_PLIST ${CMAKE_CURRENT_SOURCE_DIR}/renderer/Info.plist.in
  OUTPUT_NAME viewer)
target_include_directories(viewer PRIVATE renderer renderer/hud net)
target_compile_options(viewer PRIVATE -fobjc-arc)
# The start screen finds game data in the app bundle, else here (build tree).
if(NOT MR_DIST)
  target_compile_definitions(viewer PRIVATE MR_PROJECT_DATA="${CMAKE_CURRENT_SOURCE_DIR}/../data")
  target_compile_definitions(viewer PRIVATE MR_PROJECT_SOURCE="${CMAKE_CURRENT_SOURCE_DIR}")
endif()
target_link_libraries(viewer PRIVATE ao_net ao_all PkgConfig::AUDIO
  "-framework Metal" "-framework MetalKit" "-framework QuartzCore" "-framework ImageIO"
  "-framework CoreGraphics" "-framework CoreServices" "-framework CoreText" "-framework AVFoundation" "-framework Security")

# Network layer (multiplayer): AO 1.11.1's own network code (star protocol,
# UDP, TCPMess, LAN discovery, metaserver client) copied into net/, without
# its dialogs. Programs that link it get real networking in place of the
# core's stubs/network_stub.cpp (list ao_net before ao_all so its objects win).
file(GLOB_RECURSE AO_NET_SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/net/*.cpp)  # includes session_net.cpp
add_library(ao_net STATIC ${AO_NET_SOURCES})
target_include_directories(ao_net PUBLIC net/Network net/Network/Metaserver net/TCPMess)
target_compile_options(ao_net PRIVATE -w)
target_link_libraries(ao_net PUBLIC ao_all PkgConfig::NETDEPS)
# Automatic router port forwarding (UPnP, AO's PortForward.cpp), linked
# statically so the app bundle needs no extra library. Optional.
find_path(MINIUPNPC_INCLUDE miniupnpc/miniupnpc.h HINTS /opt/homebrew/opt/miniupnpc/include)
find_library(MINIUPNPC_STATIC NAMES libminiupnpc.a HINTS /opt/homebrew/opt/miniupnpc/lib)
if(MINIUPNPC_INCLUDE AND MINIUPNPC_STATIC)
	target_compile_definitions(ao_net PRIVATE HAVE_MINIUPNPC=1)
	target_include_directories(ao_net PRIVATE ${MINIUPNPC_INCLUDE})
	target_link_libraries(ao_net PUBLIC ${MINIUPNPC_STATIC})
	message(STATUS "UPnP port forwarding: on (${MINIUPNPC_STATIC})")
else()
	message(STATUS "UPnP port forwarding: off (brew install miniupnpc)")
endif()

# Headless network test (two copies on one machine stay in sync).
add_executable(net_test MACOSX_BUNDLE runner/net_test.cpp runner/InfoPlist.strings
  renderer/world_mesh.cpp renderer/hud/hud.cpp renderer/hud/motion_sensor.cpp
  renderer/hud/overhead_map.cpp renderer/hud/OverheadMapRenderer.cpp renderer/hud/OverheadMap_SDL.cpp)
set_target_properties(net_test PROPERTIES MACOSX_BUNDLE_INFO_PLIST ${CMAKE_CURRENT_SOURCE_DIR}/runner/Info.plist.in OUTPUT_NAME net_test)
target_include_directories(net_test PRIVATE net renderer renderer/hud)
target_link_libraries(net_test PRIVATE ao_net)

# Continuum (formerly Leland; native map editor, core/editor/): replaces the Mono/GTK Weland
# fork (tools/weland, removed 2026-11-27). Plain C++ map model + AppKit/Metal; no engine code.
# Optional: Tav's published source leaves the editor out (its source is published separately).
if(EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/editor/leland_main.mm)
add_library(leland_model STATIC editor/map_file.cpp editor/map_edit.cpp editor/shapes_file.cpp editor/terminals.cpp editor/resource_fork.cpp editor/shapes_model.cpp editor/sounds_model.cpp editor/physics_model.cpp)
target_include_directories(leland_model PUBLIC editor)
file(GLOB LELAND_FONTS ${CMAKE_CURRENT_SOURCE_DIR}/renderer/fonts/*.ttf)
# The texture library: the three games' Shapes files, renamed per game.
set(LELAND_SHAPES_DIR ${CMAKE_CURRENT_BINARY_DIR}/leland_shapes)
file(MAKE_DIRECTORY ${LELAND_SHAPES_DIR})
foreach(pair "Marathon.shps|Marathon/Marathon/Shapes.shps" "Marathon 2.shpA|Marathon2/Marathon 2/Shapes.shpA"
             "Marathon Infinity.shpA|MarathonInfinity/Marathon Infinity/Shapes.shpA")
  string(REPLACE "|" ";" parts "${pair}")
  list(GET parts 0 dst)
  list(GET parts 1 src)
  if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/../data/${src}")
    configure_file("${CMAKE_CURRENT_SOURCE_DIR}/../data/${src}" "${LELAND_SHAPES_DIR}/${dst}" COPYONLY)
    list(APPEND LELAND_SHAPES "${LELAND_SHAPES_DIR}/${dst}")
  endif()
endforeach()
add_executable(Continuum MACOSX_BUNDLE editor/leland_main.mm editor/map_view.mm editor/inspector.mm editor/texture_palette.mm editor/view3d.mm editor/obj_export.mm editor/axiom.mm editor/images_file.mm editor/cardinal.mm editor/cardinal_sounds.mm editor/cardinal_physics.mm editor/lens.mm
  ${CMAKE_CURRENT_SOURCE_DIR}/../tools/icon/Continuum.icns ${LELAND_FONTS} ${LELAND_SHAPES})
set_source_files_properties(${LELAND_SHAPES} PROPERTIES MACOSX_PACKAGE_LOCATION Resources/Shapes)
# Doom WAD import (File > Import Doom WAD): the Python converter and map builder.
set(LELAND_TOOL ${CMAKE_CURRENT_SOURCE_DIR}/../tools/doom2marathon.py ${CMAKE_CURRENT_SOURCE_DIR}/../tools/doom_planar.py ${CMAKE_CURRENT_SOURCE_DIR}/../tools/doom_udmf.py ${CMAKE_CURRENT_SOURCE_DIR}/../tools/doom_textures.py ${CMAKE_CURRENT_SOURCE_DIR}/../tools/doom_acs.py ${CMAKE_CURRENT_SOURCE_DIR}/../tools/acs_vm.lua)
set(LELAND_TOOL_LIB ${CMAKE_CURRENT_SOURCE_DIR}/../tools/mapgen/mapbuild.py ${CMAKE_CURRENT_SOURCE_DIR}/../tools/mapgen/wad.py)
target_sources(Continuum PRIVATE ${LELAND_TOOL} ${LELAND_TOOL_LIB})
set_source_files_properties(${LELAND_TOOL} PROPERTIES MACOSX_PACKAGE_LOCATION Resources/Tools)
set_source_files_properties(${LELAND_TOOL_LIB} PROPERTIES MACOSX_PACKAGE_LOCATION Resources/Tools/mapgen)
if(MR_DIST)   # no paths from this Mac in a copy to hand out
  target_compile_definitions(Continuum PRIVATE LELAND_PROJECT_DATA="")
else()
  target_compile_definitions(Continuum PRIVATE LELAND_PROJECT_DATA="${CMAKE_CURRENT_SOURCE_DIR}/../data")
endif()
set_source_files_properties(${LELAND_FONTS} PROPERTIES MACOSX_PACKAGE_LOCATION Resources/Fonts)
set_source_files_properties(${CMAKE_CURRENT_SOURCE_DIR}/../tools/icon/Continuum.icns PROPERTIES MACOSX_PACKAGE_LOCATION Resources)
set_target_properties(Continuum PROPERTIES MACOSX_BUNDLE_INFO_PLIST ${CMAKE_CURRENT_SOURCE_DIR}/editor/Info.plist.in OUTPUT_NAME Continuum)
target_compile_options(Continuum PRIVATE -fobjc-arc)
target_link_libraries(Continuum PRIVATE leland_model "-framework AVFoundation" "-framework Cocoa" "-framework Metal" "-framework MetalKit"
  "-framework QuartzCore" "-framework ImageIO" "-framework UniformTypeIdentifiers" "-framework CoreText")
add_executable(leland_roundtrip editor/roundtrip_main.cpp)
target_link_libraries(leland_roundtrip PRIVATE leland_model)
add_executable(physics_test editor/physics_test_main.cpp)
target_link_libraries(physics_test PRIVATE leland_model)
add_executable(sounds_test editor/sounds_test_main.cpp)
target_link_libraries(sounds_test PRIVATE leland_model)
add_executable(shapes_test editor/shapes_test_main.cpp)
target_link_libraries(shapes_test PRIVATE leland_model)
add_executable(union_test editor/union_test_main.cpp)
target_link_libraries(union_test PRIVATE leland_model)
add_executable(levels_test editor/levels_test_main.cpp)
target_link_libraries(levels_test PRIVATE leland_model)
add_executable(terminals_test editor/terminals_test_main.cpp)
target_link_libraries(terminals_test PRIVATE leland_model)
add_executable(leland_edit_test editor/edit_test_main.cpp)
target_link_libraries(leland_edit_test PRIVATE leland_model)
endif()
